﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FetchXmlTool
{
    public partial class ConnectionsForm : Form
    {
        List<ConnectionStringSettings> connectionStringSettingsList;

        public ConnectionsForm()
        {
            InitializeComponent();
        }

        private void ConnectionsForm_Shown(object sender, EventArgs e)
        {
            connectionStringSettingsList = ((FetchXmlEvaluator)this.Owner).connectionStringSettingsList;

            dataGridViewConnectionStrings.Rows.Clear();
            foreach (ConnectionStringSettings item in connectionStringSettingsList)
                dataGridViewConnectionStrings.Rows.Add(item.Name, item.ConnectionString);
        }

        private void buttonConfirm_Click(object sender, EventArgs e)
        {
            connectionStringSettingsList.Clear();

            foreach (DataGridViewRow row in dataGridViewConnectionStrings.Rows)
            {
                if (row.Cells[0].Value == null || row.Cells[1].Value == null ||
                    String.IsNullOrEmpty(row.Cells[0].Value.ToString()) || String.IsNullOrEmpty(row.Cells[1].Value.ToString()))
                    continue;

                connectionStringSettingsList.Add(new ConnectionStringSettings(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()));
            }

            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (configuration == null)
                return;

            configuration.ConnectionStrings.ConnectionStrings.Clear();
            foreach (var item in connectionStringSettingsList)
                configuration.ConnectionStrings.ConnectionStrings.Add(item);

            configuration.Save();

            Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
